<?php

namespace App\Service\FuYou;


use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Http\Form\KfCashRegisterV2\KfCashRegisterV2FormAttribute;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Models\FuYou\WorkOrderFuyouInfoModel;
use App\Models\FuYou\WorkOrderFuyouLogModel;
use App\Models\Fy\FyRegionBankModel;
use App\Models\Fy\FyRegionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderMissionModel;
use App\Remote\FuYou\FuYouRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\EmailService;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\SiteLocation\SiteLocationConvert;
use App\Service\System\SystemNotifyService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FuYouService
{
    const FUYOU_BACK_SUC_CODE                    = '0000';//操作成功
    const FUYOU_BACK_SHOP_REPEAT_CODE            = '1001';//商户名重复
    const FUYOU_BACK_PARAMS_ERR_CODE             = '2001';//参数格式错误
    const FUYOU_BACK_MCHNT_NOT_FOUND_CODE        = '2002';//未找到商户
    const FUYOU_BACK_MCHNT_EXIST_CODE            = '2003';//商户已审核通过
    const FUYOU_BACK_MCHNT_CHANGE_NOT_FOUND_CODE = '2004';//商户入账变更信息不存在
    const FUYOU_BACK_MERCHANT_NOT_FOUND_CODE     = '2005';//渠道商户不存在
    const FUYOU_BACK_NOT_FILE_CODE               = '2011';//附件不存在
    const FUYOU_BACK_NOT_MCHNT_CODE              = '2103';//商户未开通，请开通商户！
    const FUYOU_BACK_MCHNT_MORE_DAY_CODE         = '5001';//当天入网商户数超限
    const FUYOU_BACK_MCHNT_EXIST_MORE_CODE       = '7001';//商户存在多账户，无法更新【只能在平台更新】
    const FUYOU_BACK_NOT_FOUND_FILE_CODE         = '9996';//未找到文件
    const FUYOU_BACK_SIGN_ERR_CODE               = '9997';//报文验签失败
    const FUYOU_BACK_REQ_ERR_CODE                = '9998';//报文格式错误


    const RETURN_SUCCESS_CODE = 'SUCCESS';//请求-商户渠道子商户号查询接口 返回成功
    const RETURN_FAIL_CODE    = 'FAIL';   //请求-商户渠道子商户号查询接口 返回失败

    const paramsMap = [//字段问题中英文对应
        'mchnt_name'            => '商户全称-需与营业执照一致',                                                                                                                                                                                                               //商户全称，不能有特殊字符，仅可包含汉字、数字、字母
        'mchnt_shortname'       => '商户简称',                                                                                                                                                                                                                        //商户简称，不能有特殊字符，仅可包含汉字、数字、字母
        'real_name'             => '商户真实名称(与营业执照上相同)',                                                                                                                                                                                                            //商户真实名称(与营业执照上相同)
        'license_type'          => '证件类型',                                                                                                                                                                                                                        //证件类型：0 企业商户：营业执照（license_no填15位长的营业执照编号）1 企业商户：三证合一（license_no填18位长的三证合一营业执照编号）A 小微商户：身份证(一证下机)B 个体户工商户（个体工商户不论证件是营业执照还是三证合一都传 B）2 事业单位
        'license_no'            => '证件号码',                                                                                                                                                                                                                        //证件号码，填写方法：1.license_type=0 或 1 或 2，此处填写营业执照号码。2.license_type=A，此处填写身份证号码3.license_type=B，此处填写个体工商户营业执照号码
        'license_expire_dt'     => '证件到期日（格式yyyyMMdd）',                                                                                                                                                                                                           //证件到期日（格式yyyyMMdd）长期请填20991231，无有效期请填190001011.license_type=0 或 1 或 2，此处填写营业执照到期日。2.license_type=A，此处填写身份证的到期日3.license_type=B，此处填写个体工商户营业执照号的到期日
        'certif_id'             => '法人身份证号',                                                                                                                                                                                                                      //法人身份证号
        'certif_id_expire_dt'   => '法人身份证到期日（格式 YYYYMMDD）',                                                                                                                                                                                                       //法人身份证到期日（格式 YYYYMMDD）
        'contact_person'        => '联系人姓名（不能有特殊字符）',                                                                                                                                                                                                              //联系人姓名（不能有特殊字符）
        'contact_phone'         => '客服电话，必须纯数字。推荐 400开头电话或11位有效手机号',                                                                                                                                                                                              //客服电话，必须纯数字。推荐 400开头电话或11位有效手机号
        'contact_addr'          => '商户经营地联系地址',                                                                                                                                                                                                                   //商户经营地联系地址
        'contact_mobile'        => '联系电话',                                                                                                                                                                                                                        //联系电话
        'business'              => '经营范围代码（新开户则必填）见附件4.微信经营范围代码',                                                                                                                                                                                                 //经营范围代码（新开户则必填）见附件4.微信经营范围代码
        'city_cd'               => '商户经营地市代码见附件6.省市区代码对照表',                                                                                                                                                                                                       //商户经营地市代码见附件6.省市区代码对照表
        'county_cd'             => '商户经营地区县代码（必须属于 city_cd 所辖）见附件6.省市区代码对照表',                                                                                                                                                                                     //商户经营地区县代码（必须属于 city_cd 所辖）见附件6.省市区代码对照表
        'acnt_type'             => '入账卡类型：1：对公；2：对私;',                                                                                                                                                                                                            //入账卡类型：1：对公；2：对私;入账卡类型为 1 时，对公户户名需与营业执照名称保持一致（进件若为双账户时，此处必填 2 ，即对私结算）
        'bank_type'             => '行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表',                                                                                                                                                                                      //行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表
        'inter_bank_no'         => '入账卡开户行联行号见附件9.开户行信息列表',                                                                                                                                                                                                       //入账卡开户行联行号 对公户和城商行，农商行，农信社必填，否则影响银行卡入账。如果联行号在富友给的表格里不存在，可联系运营人员添加见附件9.开户行信息列表
        'iss_bank_nm'           => '入账卡开户行名称见附件9.开户行信息列表',                                                                                                                                                                                                        //入账卡开户行名称见附件9.开户行信息列表
        'acnt_nm'               => '入账卡户名',                                                                                                                                                                                                                       //入账卡户名1. 如果 license_type=A，acnt_nm=artif_nm 即小微商户身份证入网须入账法人2. 如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致3. 如果 acnt_type=1 且acnt_artif_flag=1，则 acnt_nm=real_name 即对公且法人入账，则入账卡户名和营业执照上商户名一致
        'acnt_no'               => '入账卡号（不带长度位）',                                                                                                                                                                                                                 //入账卡号（不带长度位）
        'settle_tp'             => '清算类型：1 自动结算（T1）；',                                                                                                                                                                                                            //清算类型：1 自动结算（T1）
        'artif_nm'              => '法人姓名',                                                                                                                                                                                                                        //法人姓名（如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致）
        'acnt_artif_flag'       => '法人入账标识 0 :非法人入账，1：法人入账',                                                                                                                                                                                                      //法人入账标识 0 :非法人入账，1：法人入账 若license_type=A，这此字段必须填：1：法人入账
        'acnt_certif_tp'        => '入账证件类型("0":"身份证"【默认】',                                                                                                                                                                                                        //入账证件类型("0":"身份证"【默认】【acnt_artif_flag = 0 时必填】
        'acnt_certif_expire_dt' => '入账证件到期日（格式 yyyyMMdd）',                                                                                                                                                                                                                       //入账证件到期日（格式 yyyyMMdd）license_type=A，这里的值acnt_certif_expire_dt=license_expire_dt
        'acnt_certif_id'        => '入账证件号',                                                                                                                                                                                                        //入账证件号【acnt_artif_flag = 0时必填】1.如果 license_type=A，则acnt_certif_id =license_no 即小微商户身份证入网须入账人身份证号码即法人身份证号码2.如果 acnt_type=2 且acnt_artif_flag=1，则acnt_certif_id =certif_id 即对私且法人入账，则入账卡人身份证号码和法人身份证号码一致
        "card_start_dt"         => '法人身份证开始时间',                                                                                                                                                                                                                    //法人身份证开始时间(2021年9月10日后必填)
        "contact_cert_no"       => '联系人身份证号',                                                                                                                                                                                                                     //联系人身份证号(9月10日后必填)
        "lic_regis_addr"        => '营业执照注册地址',                                                                                                                                                                                                                 //营业执照注册地址
        "license_start_dt"      => '营业执照开始时间',                                                                                                                                                                                                                    //营业执照开始时间
//        参数格式错误:请填写对应的对公账户！=> 入账卡开户行名称 见附件9.开户行信息列表
    ];

    /**
     * 商户信息登记接口
     * @param $data
     * @param int $flagRepeatName
     * @return mixed
     * @throws GuzzleException
     */
    public function wxMchntAdd($data, $flagRepeatName = 0): array
    {
        //获取工单信息
        $res          = WorkOrderApplyContentModel::getApplyContentByWorkOrderNo($data['workOrderNo']);
        $contentArray = json_decode($res['content'], true);
        if (!$contentArray) {
            $contentArray = array($data, $contentArray);
        }
        $formData = (new FuYouService)->getFromData($contentArray, $flagRepeatName);//表单数据转化

        $params = [
            'mchnt_name'            => $formData['mchntFullName'],                                                                                                                     //商户全称，不能有特殊字符，仅可包含汉字、数字、字母
            'mchnt_shortname'       => $formData['mchntShortname'],                                                                                                                    //商户简称，不能有特殊字符，仅可包含汉字、数字、字母
            'real_name'             => $formData['mchntName'],                                                                                                                         //商户真实名称(与营业执照上相同)
            'license_type'          => $formData['licenseType'],                                                                                                                       //证件类型：0 企业商户：营业执照（license_no填15位长的营业执照编号）1 企业商户：三证合一（license_no填18位长的三证合一营业执照编号）A 小微商户：身份证(一证下机)B 个体户工商户（个体工商户不论证件是营业执照还是三证合一都传 B）2 事业单位
            'license_no'            => $contentArray['businessLicenseNumber'],                                                                                                         //证件号码，填写方法：1.license_type=0 或 1 或 2，此处填写营业执照号码。2.license_type=A，此处填写身份证号码3.license_type=B，此处填写个体工商户营业执照号码
            'license_expire_dt'     => $formData['certifIdExpireDt'] ?? '20991231',                                                                                                    //证件到期日（格式yyyyMMdd）长期请填20991231，无有效期请填190001011.license_type=0 或 1 或 2，此处填写营业执照到期日。2.license_type=A，此处填写身份证的到期日3.license_type=B，此处填写个体工商户营业执照号的到期日
            'certif_id'             => $contentArray['legalPersonIdentityCardNumber'],                                                                                                 //法人身份证号
            'certif_id_expire_dt'   => $formData['licenseExpireDt'] ?? '20991231',                                                                                                     //法人身份证到期日（格式 YYYYMMDD）
            'contact_addr'          => $contentArray['businessPremises'] ?? '',                                                                                                        //商户经营地联系地址
            'business'              => $formData['business'],                                                                                                                          //经营范围代码（新开户则必填）见附件4.微信经营范围代码
            'city_cd'               => $formData['cityCd'],                                                                                                                            //商户经营地市代码见附件6.省市区代码对照表
            'county_cd'             => $formData['countyCd'],                                                                                                                          //商户经营地区县代码（必须属于 city_cd 所辖）见附件6.省市区代码对照表
            'acnt_type'             => $formData['acntType'],                                                                                                                          //入账卡类型：1：对公；2：对私;入账卡类型为 1 时，对公户户名需与营业执照名称保持一致（进件若为双账户时，此处必填 2 ，即对私结算）
            'bank_type'             => $formData['bankCode'],                                                                                                                          //行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表
            'inter_bank_no'         => $formData['interBankNo'],                                                                                                                       //入账卡开户行联行号 对公户和城商行，农商行，农信社必填，否则影响银行卡入账。如果联行号在富友给的表格里不存在，可联系运营人员添加见附件9.开户行信息列表
            'iss_bank_nm'           => $formData['issBankNm'],                                                                                                                         //入账卡开户行名称见附件9.开户行信息列表
            'acnt_nm'               => $formData['acntNm'],                                                                                                                            //入账卡户名1. 如果 license_type=A，acnt_nm=artif_nm 即小微商户身份证入网须入账法人2. 如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致3. 如果 acnt_type=1 且acnt_artif_flag=1，则 acnt_nm=real_name 即对公且法人入账，则入账卡户名和营业执照上商户名一致
            'acnt_no'               => $formData['acntNo'],                                                                                                                            //入账卡号（不带长度位）
            'settle_tp'             => '1',                                                                                                                                            //清算类型：1 自动结算（T1）
            'artif_nm'              => $formData['artifNm'],                                                                                                                           //法人姓名（如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致）
            'acnt_artif_flag'       => $formData['acntArtifFlag'],                                                                                                                     //法人入账标识 0 :非法人入账，1：法人入账 若license_type=A，这此字段必须填：1：法人入账
            'acnt_certif_tp'        => 0,                                                                                                                                              //入账证件类型("0":"身份证"【默认】【acnt_artif_flag = 0 时必填】
            'acnt_certif_expire_dt' => $formData['certifIdExpireDt'] ?? '20991231',                                                                                                    //入账证件到期日（格式 yyyyMMdd）license_type=A，这里的值acnt_certif_expire_dt=license_expire_dt
            'acnt_certif_id'        => $formData['entryIDNumber'],                                                                                                                     //入账证件号【acnt_artif_flag = 0时必填】1.如果 license_type=A，则acnt_certif_id =license_no 即小微商户身份证入网须入账人身份证号码即法人身份证号码2.如果 acnt_type=2 且acnt_artif_flag=1，则acnt_certif_id =certif_id 即对私且法人入账，则入账卡人身份证号码和法人身份证号码一致
            "card_start_dt"         => $formData['licenseStartDt'],                                                                                                                    //法人身份证开始时间(2021年9月10日后必填)
            "contact_cert_no"       => $contentArray['legalPersonIdentityCardNumber'],                                                                                                 //联系人身份证号(9月10日后必填)
            "lic_regis_addr"        => $contentArray['businessPremises'],                                                                                                              //营业执照注册地址
            "license_start_dt"      => $formData['cardStartDt'],                                                                                                                       //营业执照开始时间
            "acnt_contact_mobile"   => $contentArray['legalPersonBankCardReserveMobile'] ?? '',                                                                                        //对私户入账手机号
            "has_reserve_acnt"      => $formData['hasReserveAcnt'] ?? '',                                                                                                              //是否有备用对公银行账号(1：有，0：没有)
            "reserve_acnt_no"       => $formData['reserveAcntNo'] ?? '',                                                                                                               //双账户对公卡卡号
            "reserve_acnt_nm"       => $formData['reserveAcntNm'] ?? '',                                                                                                               //双账户对公卡户名
            "reserve_inter_bank_no" => $formData['reserveInterBankNo'] ?? '',                                                                                                          //双账户对公卡联行号
            "reserve_iss_bank_nm"   => $formData['reserveIssBankNm'] ?? '',                                                                                                            //双账户对公卡开户行名称
            "reserve_bank_type"     => $formData['reserveBankType'] ?? '',                                                                                                             //双账户对公卡行别
        ];
        $fuYouRemote = (new FuYouRemote());
        $res         = $fuYouRemote->wxMchntAdd($params);//商户信息登记接口

        self::addLog($data['workOrderNo'], $params, 0, '');//记录第一次提交信息

        if ($res['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res['ret_msg'];// 错误信息
            switch ($res['ret_code']) {
                case self::FUYOU_BACK_SHOP_REPEAT_CODE://商户名重复- 重试把商户号 追加数字
                    $flagRepeatName = $formData['flagRepeatName'] ?? 0;
                    if ($flagRepeatName <= 11) {// 同一入账人，通过接口最多入网十次
                        return (new FuYouService)->wxMchntAdd($data, $flagRepeatName + 1);
                    }
                    break;
                case self::FUYOU_BACK_PARAMS_ERR_CODE://参数格式错误-需驳回重新修改资料
                    foreach (self::paramsMap as $k => $v) {
                        $resMsg = str_replace($k, $v, $resMsg);
                    }
                    break;
            }

            self::updateWorkOrder($data, $params, $res['ret_code'], $resMsg);
            return [];
        }

        //随机取店铺审核配图-匹配店铺类型 todo type-商场和街边
        $shopImgConfig = self::getShopImg($data['shopId']);
        $shopImg       = ['doorHeaderImg' => '', 'frontImg' => ''];
        if ($shopImgConfig) {
            $count   = count($shopImgConfig);
            $shopImg = $shopImgConfig[rand(0, $count - 1)];
        }
        $addData = [
            'workOrderNo'        => $data['workOrderNo'],
            'fyMchntCd'          => $res['fy_mchnt_cd'],                                                //生成的富友商户号
            'shopImg'            => json_encode($shopImg),                                              //店铺审核图片 doorHeaderImg-门头照 frontImg-门脸照
            'weChatAuthorizeImg' => $fuYouRemote->wxAuthorizeImg,                                       //微信授权二维码图片
            'alipayAuthorizeImg' => $fuYouRemote->alipayAuthorizeImg,                                   //支付宝授权二维码图片
            'companyName'        => $formData['mchntName'],                                             //企业名称
            'step'               => WorkOrderFuyouInfoModel::DEFAULT_STEP_AUDIT,                        //审核中--富友接口资料审核
        ];
        WorkOrderFuyouInfoModel::addInfo($addData);
        WorkOrderApplyMainModel::saveStep($data['workOrderNo'], MissionEnum::STEP_7);
        //信息修改成功后-下一步
        self::ftpUpImg(['workOrderNo' => $data['workOrderNo'], 'fyMchntCd' => $res['fy_mchnt_cd'], 'companyName' => $formData['mchntName']], $shopImg);//上传图片
        return [];
    }


    /**
     * 商户信息更新接口
     * @param $data
     * @param int $flagRepeatName
     * @return mixed
     * @throws GuzzleException
     */
    public static function wxMchntUpd($data, $flagRepeatName = 0): array
    {
        //获取工单信息
        $res          = WorkOrderApplyContentModel::getApplyContentByWorkOrderNo($data['workOrderNo']);
        $contentArray = json_decode($res['content'], true);
        if (!$contentArray) {
            return [];
        }

        $getFuyouInfo = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);//富友商户信息表
        if(!$getFuyouInfo){
            return [];
        }
        $fuYouRemote    = new FuYouRemote();
        $getFuyouConfig = $fuYouRemote->getMchntInfAndConfig(['mchntCd' => $getFuyouInfo['fyMchntCd']]);//商户信息查询接口

        if ($getFuyouConfig['retCode'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $getFuyouConfig['retMsg'];// 错误信息
            switch ($getFuyouConfig['retCode']) {
                case self::FUYOU_BACK_MCHNT_NOT_FOUND_CODE://未找到商户
                    break;
            }
            self::updateWorkOrder($data, ['mchntCd' => $getFuyouInfo['fyMchntCd']], $getFuyouConfig['retCode'], $resMsg);
            return [];
        }
        $formData = (new FuYouService)->getFromData($contentArray, $flagRepeatName);//表单数据转化

        $params = [
            'fy_mchnt_cd'           => $getFuyouInfo['fyMchntCd'],                                                                                                                                                                                                                                                                                                                                      //已在富友入网的富友商户代码
            'mchnt_name'            => $getFuyouConfig['mchntName'] != $formData['mchntFullName'] ? $formData['mchntFullName'] : '',                                                                                                                                                                                                                                                                            //商户全称，不能有特殊字符，仅可包含汉字、数字、字母
            'mchnt_shortname'       => $getFuyouConfig['mchntShortname'] != $formData['mchntShortname'] ? $formData['mchntShortname'] : '',                                                                                                                                                                                                                                                             //商户简称，不能有特殊字符，仅可包含汉字、数字、字母
            'real_name'             => $getFuyouConfig['realName'] != $formData['mchntName'] ? $formData['mchntName'] : '',                                                                                                                                                                                                                                                                               //商户真实名称(与营业执照上相同)
            'license_type'          => $getFuyouConfig['licenseType'] != $formData['licenseType'] ? $formData['licenseType'] : '',                                                                                                                                                                                                                                                                      //证件类型：0 企业商户：营业执照（license_no填15位长的营业执照编号）1 企业商户：三证合一（license_no填18位长的三证合一营业执照编号）A 小微商户：身份证(一证下机)B 个体户工商户（个体工商户不论证件是营业执照还是三证合一都传 B）2 事业单位
            'license_no'            => $getFuyouConfig['licenseNo'] != $contentArray['businessLicenseNumber'] ? $contentArray['businessLicenseNumber'] : '',                                                                                                                                                                                                                                            //证件号码，填写方法：1.license_type=0 或 1 或 2，此处填写营业执照号码。2.license_type=A，此处填写身份证号码3.license_type=B，此处填写个体工商户营业执照号码
            'license_expire_dt'     => $getFuyouConfig['licenseExpireDt'] != $formData['certifIdExpireDt'] ? $formData['certifIdExpireDt'] : '',                                                                                                                                                                                                                                                        //证件到期日（格式yyyyMMdd）长期请填20991231，无有效期请填190001011.license_type=0 或 1 或 2，此处填写营业执照到期日。2.license_type=A，此处填写身份证的到期日3.license_type=B，此处填写个体工商户营业执照号的到期日
            'certif_id'             => $getFuyouConfig['certifId'] != $contentArray['legalPersonIdentityCardNumber'] ? $contentArray['legalPersonIdentityCardNumber'] : '',                                                                                                                                                                                                                             //法人身份证号
            'certif_id_expire_dt'   => $getFuyouConfig['certifIdExpireDt'] != $formData['licenseExpireDt'] ? $formData['licenseExpireDt'] : '',                                                                                                                                                                                                                                                         //法人身份证到期日（格式 YYYYMMDD）
            'contact_addr'          => $getFuyouConfig['contactAddr'] != $contentArray['businessPremises'] ? $contentArray['businessPremises'] : '',                                                                                                                                                                                                                                                    //商户经营地联系地址
            //            'city_cd'               => $formData['cityCd'],                                                                                                                                                                                                                                                                                                                                   //商户经营地市代码见附件6.省市区代码对照表
            //            'county_cd'             => $formData['countyCd'],                                                                                                                                                                                                                                                                                                                                 //商户经营地区县代码（必须属于 city_cd 所辖）见附件6.省市区代码对照表
            'acnt_type'             => $formData['acntType'],                                                                                                                                                                                                                                                                                                                                           //入账卡类型：1：对公；2：对私;入账卡类型为 1 时，对公户户名需与营业执照名称保持一致（进件若为双账户时，此处必填 2 ，即对私结算）
            'bank_type'             => $formData['bankCode'],                                                                                                                                                                                                                                                                                                                        //行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表
            'inter_bank_no'         => $formData['interBankNo'],                                                                                                                                                                                                                                                                                                                  //入账卡开户行联行号 对公户和城商行，农商行，农信社必填，否则影响银行卡入账。如果联行号在富友给的表格里不存在，可联系运营人员添加见附件9.开户行信息列表
            'iss_bank_nm'           => $formData['issBankNm'],                                                                                                                                                                                                                                                                                                                                          //入账卡开户行名称见附件9.开户行信息列表
            'acnt_nm'               => $formData['acntNm'] ?? '',                                                                                                                                                                                                                                                                               //入账卡户名1. 如果 license_type=A，acnt_nm=artif_nm 即小微商户身份证入网须入账法人2. 如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致3. 如果 acnt_type=1 且acnt_artif_flag=1，则 acnt_nm=real_name 即对公且法人入账，则入账卡户名和营业执照上商户名一致
            'acnt_artif_flag'       => $formData['acntArtifFlag'],                                                                                                                                                                                                                                                                                                                                                               //法人入账标识 0 :非法人入账，1：法人入账 若license_type=A，这此字段必须填：1：法人入账
            'acnt_no'               => $formData['acntNo'],                                                                                                                                                                                                                                                                                                                                             //入账卡号（不带长度位）
            'artif_nm'              => $formData['artifNm'] ?? '',                                                                                                                                                                                                                                                                               //法人姓名（如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致）
            'acnt_certif_expire_dt' => $getFuyouConfig['certifIdExpireDt'] != $formData['licenseExpireDt'] ? $formData['licenseExpireDt'] : '',                                                                                                                                                                                                                                                         //入账证件到期日（格式 yyyyMMdd）license_type=A，这里的值acnt_certif_expire_dt=license_expire_dt
            'acnt_certif_id'        => $getFuyouConfig['certifId'] != $formData['entryIDNumber'] ? $formData['entryIDNumber'] : '',                                                                                                                                                                                                                             //入账证件号【acnt_artif_flag = 0时必填】1.如果 license_type=A，则acnt_certif_id =license_no 即小微商户身份证入网须入账人身份证号码即法人身份证号码2.如果 acnt_type=2 且acnt_artif_flag=1，则acnt_certif_id =certif_id 即对私且法人入账，则入账卡人身份证号码和法人身份证号码一致
            "card_start_dt"         => $formData['licenseStartDt'],                                                                                                                                                                                                                                                                                                                                     //法人身份证开始时间(2021年9月10日后必填)
            "contact_cert_no"       => $getFuyouConfig['certifId'] != $contentArray['legalPersonIdentityCardNumber'] ? $contentArray['legalPersonIdentityCardNumber'] : '',                                                                                                                                                                                                                             //联系人身份证号(9月10日后必填)
            "lic_regis_addr"        => $getFuyouConfig['licRegisAddr'] != $contentArray['businessPremises'] ? $contentArray['businessPremises'] : '',                                                                                                                                                                                                                                                   //营业执照注册地址
            "license_start_dt"      => $formData['cardStartDt'] ?? '',                                                                                                                                                                                                                                                                                                                                  //营业执照开始时间
            'acnt_contact_mobile'   => $contentArray['legalPersonBankCardReserveMobile'] ?? '',                                                                                        //对私户入账手机号
        ];


        $res = $fuYouRemote->wxMchntUpd($params);//商户信息更新接口

        if ($res['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res['ret_msg'];// 错误信息
            switch ($res['ret_code']) {
                case self::FUYOU_BACK_SHOP_REPEAT_CODE://商户名重复- 重试把商户号 追加数字
                    $flagRepeatName = $formData['flagRepeatName'] ?? 0;
                    if ($flagRepeatName <= 11) {// 同一入账人，通过接口最多入网十次
                        return (new FuYouService)->wxMchntUpd($data, $flagRepeatName + 1);
                    }
                    break;
                case self::FUYOU_BACK_PARAMS_ERR_CODE://参数格式错误-需驳回重新修改资料
                    foreach (self::paramsMap as $k => $v) {
                        $resMsg = str_replace($k, $v, $resMsg);
                    }
                    break;
            }
            self::updateWorkOrder($data, $params, $res['ret_code'], $resMsg);
            return [];
        }
        /*$params = [
            'fy_mchnt_cd'           => $getFuyouInfo['fyMchntCd'],                                                                                                                                                                                                                                                                                                                                      //已在富友入网的富友商户代码
            'bank_type'             => $formData['bankCode'],                                                                                                                                                                                                                                                                                                                                           //行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表
            'inter_bank_no'         => $formData['interBankNo'],                                                                                                                                                                                                                                                                                                                                        //入账卡开户行联行号 对公户和城商行，农商行，农信社必填，否则影响银行卡入账。如果联行号在富友给的表格里不存在，可联系运营人员添加见附件9.开户行信息列表
            'iss_bank_nm'           => $formData['issBankNm'],                                                                                                                                                                                                                                                                                                                                          //入账卡开户行名称见附件9.开户行信息列表
            'acnt_type'             => $formData['acntType'],                                                                                                                                                                                                                                                                                                                                           //入账卡类型：1：对公；2：对私;入账卡类型为 1 时，对公户户名需与营业执照名称保持一致（进件若为双账户时，此处必填 2 ，即对私结算）
            'acnt_nm'               => $formData['acntNm'],                                                                                                                                                                                                                                                                                                                                             //入账卡户名1. 如果 license_type=A，acnt_nm=artif_nm 即小微商户身份证入网须入账法人2. 如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致3. 如果 acnt_type=1 且acnt_artif_flag=1，则 acnt_nm=real_name 即对公且法人入账，则入账卡户名和营业执照上商户名一致
            'acnt_no'               => $formData['acntNo'],                                                                                                                                                                                                                                                                                                                                             //入账卡号（不带长度位）
            'acnt_artif_flag'       => 1,                                                                                                                                                                                                                                                                                                                                                               //法人入账标识 0 :非法人入账，1：法人入账 若license_type=A，这此字段必须填：1：法人入账
            'acnt_certif_tp'        => 0,                                                                                                                                                                                                                                                                                                                                                               //入账证件类型("0":"身份证"【默认】【acnt_artif_flag = 0 时必填】
            'acnt_certif_id'        => $contentArray['legalPersonIdentityCardNumber'],                                                                                                                                                                                                                                                                                                                  //入账证件号【acnt_artif_flag = 0时必填】1.如果 license_type=A，则acnt_certif_id =license_no 即小微商户身份证入网须入账人身份证号码即法人身份证号码2.如果 acnt_type=2 且acnt_artif_flag=1，则acnt_certif_id =certif_id 即对私且法人入账，则入账卡人身份证号码和法人身份证号码一致
            'acnt_certif_expire_dt' => $formData['certifIdExpireDt'] ?? '20991231',                                                                                                                                                                                                                                                                                                                     //入账证件到期日（格式 yyyyMMdd）license_type=A，这里的值acnt_certif_expire_dt=license_expire_dt
            "acnt_contact_mobile"   => $contentArray['legalPersonBankCardReserveMobile'] ?? '',                                                                                                                                                                                                                                                                                                         //对私户入账手机号
        ];
        $res    = (new FuYouRemote())->mchntAcntUpd($params);//入账信息变更接口

        if ($res['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res['ret_msg'];// 错误信息
            switch ($res['ret_code']) {
                case self::FUYOU_BACK_PARAMS_ERR_CODE://参数格式错误-需驳回重新修改资料
                    foreach (self::paramsMap as $k => $v) {
                        $resMsg = str_replace($k, $v, $resMsg);
                    }
                    break;
            }
            self::updateWorkOrder($data, $params, $res['ret_code'], $resMsg);
            return [];
        }*/
        if ($getFuyouInfo && $getFuyouInfo['id']) {
            WorkOrderFuyouInfoModel::setInfoById($getFuyouInfo['id'], [
                'companyName' => $formData['mchntName'],                                             //企业名称
                'step'        => WorkOrderFuyouInfoModel::DEFAULT_STEP_AUDIT,                        //审核中--富友接口资料审核
            ]);
        }
        //信息修改成功后-下一步
        self::ftpUpImg(['workOrderNo' => $data['workOrderNo'], 'fyMchntCd' => $getFuyouInfo['fyMchntCd'], 'companyName' => $formData['mchntName']]);//上传图片
        return [];
    }

    /**
     * 入账信息变更接口
     * @param $data
     * @return mixed
     * @throws GuzzleException
     */
    public static function mchntAcntUpd($data): array
    {
        //获取工单信息
        $res          = WorkOrderApplyContentModel::getApplyContentByWorkOrderNo($data['workOrderNo']);
        $contentArray = json_decode($res['content'], true);
        if (!$contentArray) {
            return [];
        }

        $params = [
            'fy_mchnt_cd'           => $data['mchntCd'],                                                                                                                                    //已在富友入网的富友商户代码
            'bank_type'             => $contentArray['bank_type'] ?? '',                                                                                                                    //行别,（acnt_type=1 必填）(参考行别对照表)见附件7.行别对照表
            'inter_bank_no'         => $contentArray['inter_bank_no'] ?? '',                                                                                                                //入账卡开户行联行号 对公户和城商行，农商行，农信社必填，否则影响银行卡入账。如果联行号在富友给的表格里不存在，可联系运营人员添加见附件9.开户行信息列表
            'iss_bank_nm'           => $contentArray['iss_bank_nm'] ?? '',                                                                                                                  //入账卡开户行名称见附件9.开户行信息列表
            'acnt_type'             => $contentArray['acnt_type'] ?? '',                                                                                                                    //入账卡类型：1：对公；2：对私;入账卡类型为 1 时，对公户户名需与营业执照名称保持一致（进件若为双账户时，此处必填 2 ，即对私结算）
            'acnt_nm'               => $contentArray['acnt_nm'] ?? '',                                                                                                                      //入账卡户名1. 如果 license_type=A，acnt_nm=artif_nm 即小微商户身份证入网须入账法人2. 如果 acnt_type=2 且acnt_artif_flag=1，则 acnt_nm=artif_nm 即对私且法人入账，则入账卡户名和法人姓名一致3. 如果 acnt_type=1 且acnt_artif_flag=1，则 acnt_nm=real_name 即对公且法人入账，则入账卡户名和营业执照上商户名一致
            'acnt_no'               => $contentArray['acnt_no'] ?? '',                                                                                                                      //入账卡号（不带长度位）
            'acnt_artif_flag'       => $contentArray['acnt_artif_flag'] ?? '',                                                                                                              //法人入账标识 0 :非法人入账，1：法人入账 若license_type=A，这此字段必须填：1：法人入账
            'acnt_certif_tp'        => $contentArray['acnt_certif_tp'] ?? '',                                                                                                               //入账证件类型("0":"身份证"【默认】【acnt_artif_flag = 0 时必填】
            'acnt_certif_id'        => $contentArray['acnt_certif_id'] ?? '',                                                                                                               //入账证件号【acnt_artif_flag = 0时必填】1.如果 license_type=A，则acnt_certif_id =license_no 即小微商户身份证入网须入账人身份证号码即法人身份证号码2.如果 acnt_type=2 且acnt_artif_flag=1，则acnt_certif_id =certif_id 即对私且法人入账，则入账卡人身份证号码和法人身份证号码一致
            'acnt_certif_expire_dt' => $contentArray['acnt_certif_expire_dt'] ?? '',                                                                                                        //入账证件到期日（格式 yyyyMMdd）license_type=A，这里的值acnt_certif_expire_dt=license_expire_dt
        ];
        $res    = (new FuYouRemote())->mchntAcntUpd($params);//商户信息登记接口

        if ($res['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res['ret_msg'];// 错误信息
            switch ($res['ret_code']) {
                case self::FUYOU_BACK_PARAMS_ERR_CODE://参数格式错误-需驳回重新修改资料
                    break;
            }
            self::updateWorkOrder($data, $params, $res['ret_code'], $resMsg);
        }
        return [];
    }

    /**
     * 商户图片上传
     * @param $data
     * @param array $shopImg
     * @return mixed
     * @throws GuzzleException
     */
    public static function ftpUpImg($data, $shopImg = []): int
    {
        //先根据工单号查询对应图片信息
        if (!$shopImg) {//店铺审核配图
            $getShopImgInfo = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);
            if ($getShopImgInfo) {
                $shopImg = json_decode($getShopImgInfo['shopImg'] ?? "", true);
            }
        }
        //获取工单信息
        $res          = WorkOrderApplyContentModel::getApplyContentByWorkOrderNo($data['workOrderNo']);
        //附件图片信息
        $resourceWorkOrderNoImg = [];
        collect($res->resourceWorkOrderNoImgRel)->each(
            function (ResourcesModel $resourcesModel) use (&$resourceWorkOrderNoImg) {
                switch ($resourcesModel->name) {
                    case 'businessLicenseImg':
                    case 'authorizationLetterImg':
                    case 'legalPersonIdentityCardFront':
                    case 'legalPersonIdentityCardBack':
                    case 'legalPersonBankCardFrontImg':
                    case 'companyBankCardImg':
                    case 'merchantRelationshipImg':
                    case 'payeeIdentityCardFront':
                    case 'payeeIdentityCardBack':
                        $resourceWorkOrderNoImg[$resourcesModel->name] = $resourcesModel->isPublic == 1 ?
                            picturePath($resourcesModel->url) : privateFilePath($resourcesModel->url);//判断是否公有图片
                        break;
                }
            }
        )->toArray(); //课程封面 （只展示一张）
        $contentArray = json_decode($res['content'], true);
        if (!$contentArray) {
            return 0;
        }

//        if ($contentArray['acnt_artif_flag'] == 0) {//非法人入账--目前没有这个类型
            $certifFlagImg     = $resourceWorkOrderNoImg['legalPersonIdentityCardFront'] ?? '';//对私账户身份证正面照片
            $certifFlagBackImg = $resourceWorkOrderNoImg['legalPersonIdentityCardBack'] ?? '';//对私账户身份证反面照片
//        }
        $certifNotFlagImg = '';

        // 其他人收款-非法人入账
        if (isset($contentArray['payeeType']) && $contentArray['payeeType'] == KfCashRegisterV2FormAttribute::PAYEE_TYPE_UN_CORPORATION) {
            $certifNotFlagImg  = $resourceWorkOrderNoImg['merchantRelationshipImg'] ?? '';             //入账非法人证明照片
            $certifFlagImg     = $resourceWorkOrderNoImg['payeeIdentityCardFront'] ?? '';              //非法人入账身份证正面照片
            $certifFlagBackImg = $resourceWorkOrderNoImg['payeeIdentityCardBack'] ?? '';               //非法人入账身份证反面照片
        }
        if ((isset($contentArray['settlementType']) && $contentArray['settlementType'] == KfCashRegisterV2FormAttribute::SETTLEMENT_TYPE_PUBLIC)
            || (isset($contentArray['businessType']) && $contentArray['businessType'] == KfCashRegisterV2FormAttribute::BUSINESS_TYPE_BUSINESS)
        ) {// 营业执照公户收款/商户类型-公司 必填公户网银截图
            $openPermitImg = $resourceWorkOrderNoImg['companyBankCardImg'] ?? '';//对公-公户网银截图
        } else {
            $openPermitImg = $resourceWorkOrderNoImg['businessLicenseImg'] ?? '';//公司 选营业执照照片
        }
        $params = [
            'mchnt_cd'          => $data['fyMchntCd'],                                                                                                                                                                //商户号
            'licenseImg'        => $resourceWorkOrderNoImg['businessLicenseImg'] ?? '',                                                                                                                               //营业执照照片 d6a4bcfed5d5c6ac.jpg
            'mchntProtocolImg'  => $resourceWorkOrderNoImg['authorizationLetterImg'] ?? '',                                                                                                                           //商户增值协议照片	 c9ccbba7d0add2e9d3d2.jpg
            'certifIdImg'       => $resourceWorkOrderNoImg['legalPersonIdentityCardFront'] ?? '',                                                                                                                     //法人身份证正面照片	 b7a8c8cbc9edb7ddd6a4c3f7d5fdc3e6.jpg
            'certifIdBackImg'   => $resourceWorkOrderNoImg['legalPersonIdentityCardBack'] ?? '',                                                                                                                      //法人身份证反面照片	 b7a8c8cbc9edb7ddd6a4c3f7b7b4c3e6.jpg
            'shopFrontImg'      => $shopImg['frontImg'],                                                                                                                                                              //门脸照片-就是内设照片		 c3c5c1b3d5d5c6ac.jpg
            'shopHeaderImg'     => $shopImg['doorHeaderImg'],                                                                                                                                                         //门头照片	 c3c5cdb7d5d5c6ac.jpg
            'certifFlagImg'     => $certifFlagImg ?? '',                                                                                                                                                              //对私账户身份证正面照片	acnt_artif_flag=0 必填 b6d4cbbdd5cbbba7c9edb7ddd6a4c3f7d5fdc3e6.jpg
            'certifFlagBackImg' => $certifFlagBackImg ?? '',                                                                                                                                                          //对私账户身份证反面照片	acnt_artif_flag=0 必填 b6d4cbbdd5cbbba7c9edb7ddd6a4c3f7b1b3c3e6.jpg
            'BankImg'           => $resourceWorkOrderNoImg['legalPersonBankCardFrontImg'] ?? '',                                                                                                                      //入账银行卡正面照片		 d2f8d0d0bfa8d5fdc3e6.jpg
            'certifNotFlagImg'  => $certifNotFlagImg,                                                                                                                                                                 //入账非法人证明照片		 c8ebd5cbb7c7b7a8c8cbd6a4c3f7.jpg
            'openPermitImg'     => $openPermitImg ?? '',                                                                                                                                                              //开户许可证照片	1.acnt_type=1对公必填2.license_type=0或1的情况即营业执照或营业执照（三证合一）入网的必填	 bfaabba7d0edbfc9d6a4.jpg
        ];

        $res = (new FuYouRemote())->ftpUpImg($params);//商户图片上传
        if (!$res) {//上传失败
            self::updateWorkOrder($data, $params, 500, '商户图片上传失败');
            return 1;
        }
        //信息修改成功后-下一步
        self::attachConfirm(array_merge($params, $data));//附件提交完成接口
        return 1;
    }

    /**
     * 附件提交完成接口(重要接口)
     * @param $data
     * @return mixed
     * @throws GuzzleException
     */
    public static function attachConfirm($data): int
    {
        $params = [
            'mchnt_cd' => $data['mchnt_cd'],                                                   //商户号
        ];
        $res    = (new FuYouRemote())->attachConfirm($params);//附件提交完成接口(重要接口)

        $res['ret_code'] = self::FUYOU_BACK_SUC_CODE;
        if ($res['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res['ret_msg'];// 错误信息
            switch ($res['ret_code']) {
                case self::FUYOU_BACK_NOT_FILE_CODE://附件不存在-重新上传
                    break;
            }

            self::updateWorkOrder($data, $params, $res['ret_code'], $resMsg);
            return 1;
        }
        //延迟一会请求-商户渠道子商户号查询接口
        sleep(2);
        self::chnlSubMchIdQueryWechat($data);
        return 1;
    }


    /**
     * 商户渠道子商户号查询接口-微信
     * @param $data
     * @return mixed
     * @throws GuzzleException
     */
    public static function chnlSubMchIdQueryWechat($data): int
    {
        $params  = [
            'mchnt_cd' => $data['mchnt_cd'],                                                        //商户号
            'mchnt_tp' => 1,                                                                        //1:微信2：支付宝3：微信绿洲4：支付宝蓝海5：翼支付6：银联二维码
        ];
        $params2 = [
            'mchnt_cd' => $data['mchnt_cd'],                                                        //商户号
            'mchnt_tp' => 2,                                                                        //1:微信2：支付宝3：微信绿洲4：支付宝蓝海5：翼支付6：银联二维码
        ];
        $fuYouRemote = new FuYouRemote();
        $res         = $fuYouRemote->chnlSubMchIdQuery($params);         //商户渠道子商户号查询接口-微信
        $res2        = $fuYouRemote->chnlSubMchIdQuery($params2);        //商户渠道子商户号查询接口-支付宝
        $addFuyouData = [];
        if ($res['return_code'] != self::RETURN_SUCCESS_CODE) {
            $resMsg = $res['result_msg'];// 错误信息
            switch ($res['return_code']) {
                case self::RETURN_FAIL_CODE://失败
                    break;
            }
            self::updateWorkOrder($data, $params, $res['return_code'], $resMsg);
            return 1;
        }
        $addFuyouData['subMchWxId']  = $res['sub_mch_id'] ?? '';   //商户子商户号
        $addFuyouData['wxChannelNo'] = $res['wx_channel_no'] ?? '';//微信渠道号
        if ($res2['return_code'] != self::RETURN_SUCCESS_CODE) {
            $resMsg = $res2['result_msg'];// 错误信息
            switch ($res2['return_code']) {
                case self::RETURN_FAIL_CODE://失败
                    break;
            }
            self::updateWorkOrder($data, $params2, $res2['return_code'], $resMsg);
            return 1;
        }
        $addFuyouData['subMchAlipayId'] = $res['sub_mch_id'] ?? '';   //商户子商户号
        if ($addFuyouData && $data['workOrderNo']) {
            $info = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);
            if ($info) {
                WorkOrderFuyouInfoModel::setInfoById($info['id'], $addFuyouData);//修改富友商户信息表
            }
        }
        WorkOrderApplyMainModel::saveStep($data['workOrderNo'], MissionEnum::STEP_8);
        //微信参数配置
        self::xyWechatConfigSet($data);
        return 1;
    }


    /**
     * 微信参数配置接口
     * @param $data
     * @return mixed
     * @throws GuzzleException
     */
    public static function xyWechatConfigSet($data): int
    {
        $params = [
            'agencyType' => $data['traceNo'] ?? '0',                                                 //代理商类型(0：一般类，1：绿洲)
            'configs'    => [                                                                                                                 //配置列表（参数如下）
                [
                    'mchntCd'        => $data['mchnt_cd'],                                                                                                                                              //富友商户号
                    'jsapiPath'      => $data['configs']['jsapiPath'] ?? '',                                                                                                                            //JSAPI 支付授权目录
                    'subAppid'       => $data['configs']['subAppid'] ?? '',                                                                                                                             //子商户 SubAPPID
                    'subscribeAppid' => $data['configs']['subscribeAppid'] ?? '',                                                                                                                       //子商户推荐关注公众账号 APPID
                ]
            ],
        ];
        $res    = (new FuYouRemote())->xyWechatConfigSet($params);//商户渠道子商户号查询接口

        if ($res['retCode'] != self::FUYOU_BACK_SUC_CODE && $res['retCode'] != self::FUYOU_BACK_MERCHANT_NOT_FOUND_CODE) {//测试-渠道商户不存在为正常
            $resMsg = $res['retMsg'];// 错误信息
            switch ($res['retCode']) {
                case self::FUYOU_BACK_MERCHANT_NOT_FOUND_CODE://渠道商户不存在
                    break;
            }

            self::updateWorkOrder($data, $params, $res['retCode'], $resMsg);
            return 1;
        }
        //成功之后app上微信/支付宝认证
        self::updateWorkOrder(
            $data, $params, 200, '成功', WorkOrderFuyouInfoModel::DEFAULT_STEP_BUSINESS_AUTHENTICATION,
            WorkOrderFuyouLogModel::DEFAULT_STATUS, MissionEnum::STEP_8
        );
        $fuYouService = new FuYouService();
        //1-发送一二级绑定邮件
        $fuYouService->secondaryBindingSendEmail($data['workOrderNo'], $data['companyName'], $data['mchnt_cd']);
        //2-发送前置系统申请邮件
        $fuYouService->preSecretApplySendEmail($data['workOrderNo'], $data['companyName'], $data['mchnt_cd']);

        // 2. 富友审核通过： - 提示加盟商，进入功能开通，收银账户开通页面进行实名认证 提示方式： 1. PUSH消息 2.短信通知 3.弹窗消息
        $applyMainModel = WorkOrderApplyMainModel::query()->where('workOrderNo', $data['workOrderNo'])->first();
        if ($applyMainModel) {
            $shopInfo = (object)current((new RmsShopApi())->getShopByIds([$applyMainModel->shopId])["data"]["shopList"]);
            $shopName = $shopInfo->name ?? '';
            if (strpos($shopName, '夸父炸串(') !== false || strpos($shopName, '夸父炸串（') !== false) {
                $shopName = str_replace(['夸父炸串(', ')', '夸父炸串（', '）'], '', $shopName);
            }
            $shopMsgSend = function () use ($shopName, $applyMainModel) {
                $pushUidMap = array_values(
                    array_column(
                        (RmsUserRemote::getShopManagerUserByShopId([$applyMainModel->shopId])['lists'] ?? []),
                        "userId"
                    )
                );

                SystemNotifyService::customerBatchPush(
                    $pushUidMap,
                    '夸父收银账号初审通过提醒',
                    "尊敬的夸父伙伴您好，" . $shopName . "申请的夸父收银账号开通，初审已通过，请点击详情进行实名认证。",
                    OrderEnum::getDetailUrl($applyMainModel),
                    $applyMainModel->shopId,
                    SystemNotifyCenterModel::NOTIFY_TYPE_5
                );
            };

            $smsMsgSend = function () use ($shopName, $applyMainModel) {
                $rmsUser = RmsUserRemote::getRmsUserByIds([$applyMainModel->createdByUid]);
                if ($rmsUser) {
                    //发送阿里云短信
                    (new SmsService())->aliyunSend(
                        current($rmsUser)["mobile"],
                        config('sms.template.workOrderOpenFunctionFYSuccess'),
                        [
                            "shopName" => $shopName,
                        ]
                    );
                }
            };
            $shopMsgSend();
            $smsMsgSend();
        }
        return 1;
    }

    /**
     * 富友微信/支付宝渠道认证获取二维码
     * @param $data
     * @return mixed
     */
    public static function getChannelAuthorize($data): array
    {
        $getInfo = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);
        if (!$getInfo) {
            return [];
        }

        $config = ConfigService::getChannelAuthorizeConfig() ?? [];
        if ($config) {
            $config = collect($config)->keyBy('type')->toArray();
        }
        return [
            'weChatAuthorizeImg'    => $config['weChat']['imgUrl'] ?? "",            //微信授权二维码图片
            'weChatAuthorizeStatus' => 0,                                            //微信授权状态 0待认证 1成功 2失败
            'weChatAuthorizeUrl'    => $config['weChat']['qrcode'] ?? "",            //微信授权二维码url
            'weChatAuthorizeFile'   => $config['weChat']['fileUrl'] ?? "",           //微信授权指引文件
            'alipayAuthorizeImg'    => $config['alipay']['imgUrl'] ?? "",            //支付宝授权二维码图片
            'alipayAuthorizeStatus' => 0,                                            //支付宝授权状态 0待认证 1成功 2失败
            'alipayAuthorizeUrl'    => $config['alipay']['qrcode'] ?? "",            //支付宝授权二维码url
            'alipayAuthorizeFile'   => $config['alipay']['fileUrl'] ?? "",           //支付宝授权指引文件
        ];
    }

    /**
     * 富友微信/支付宝渠道认证确认
     * @param $data
     * @param array $getInfo
     * @return mixed
     */
    public static function channelAuthorize($data, $getInfo = []): array
    {
        if (!$getInfo) {
            $getInfo = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);
        } else {
            $data['workOrderNo'] = $getInfo['workOrderNo'];
        }

        /*$params                = ['mchnt_cd' => $getInfo['fyMchntCd']];
        $weChatAuthorizeStatus = $alipayAuthorizeStatus = 0;                      //0待认证
        $res                   = (new FuYouRemote())->wxAuthQuery($params);       //微信认证查询接口
        $res2                  = (new FuYouRemote())->aliQueryMchChnlInf($params);//商户查询支付宝渠道信息

        if ($res['return_code'] != self::RETURN_SUCCESS_CODE) {
            $resMsg = $res['result_msg'];// 错误信息
            switch ($res['return_code']) {
                case self::RETURN_FAIL_CODE://失败
                    break;
            }
            self::updateWorkOrder(
                $data, $params, $res['return_code'], $resMsg, WorkOrderFuyouInfoModel::DEFAULT_STEP_BUSINESS_AUTHENTICATION,
                WorkOrderFuyouLogModel::DEFAULT_FAIL_STATUS, $workOrderApplyMainStep = MissionEnum::STEP_8
            );
        } else {
            $weChatAuthorizeStatus = 1;//成功
        }
        if ($res2['ret_code'] != self::FUYOU_BACK_SUC_CODE) {
            $resMsg = $res2['ret_msg'];// 错误信息
            switch ($res2['ret_code']) {
                case self::FUYOU_BACK_NOT_MCHNT_CODE://失败
                    break;
            }
            self::updateWorkOrder(
                $data, $params, $res2['ret_code'], $resMsg, WorkOrderFuyouInfoModel::DEFAULT_STEP_BUSINESS_AUTHENTICATION,
                WorkOrderFuyouLogModel::DEFAULT_FAIL_STATUS, $workOrderApplyMainStep = MissionEnum::STEP_8
            );
        } else {
            $alipayAuthorizeStatus = 1;//成功
        }*/
        $weChatAuthorizeStatus = $alipayAuthorizeStatus = 1;                      //1成功
        $data = [
            'weChatAuthorizeStatus' => $weChatAuthorizeStatus,
            'alipayAuthorizeStatus' => $alipayAuthorizeStatus,
        ];
        if ($weChatAuthorizeStatus == 1 || $alipayAuthorizeStatus == 1) {
            WorkOrderFuyouInfoModel::setInfoById($getInfo['id'], $data);
            Log::info('channelAuthorizeSuc:', ['data' => $data, 'workOrderNo' => $getInfo['workOrderNo']]);

//            if ($weChatAuthorizeStatus == 1 && $alipayAuthorizeStatus == 1) {//富友微信/支付宝渠道认证确认都完成了-流程完成 最新修改-后台完成
//                self::updateWorkOrder($data, $params, $res['return_code'], $res['retMsg'], WorkOrderFuyouLogModel::DEFAULT_STEP_SUC, WorkOrderFuyouLogModel::DEFAULT_SUC_STATUS,MissionEnum::STEP_99);
//            }
        }
        return $data;
    }

    /**
     * 写入日志
     * @param $data
     * @param $params
     * @param $resCode
     * @param $resMsg
     * @param int $step
     * @param int $status
     * @param int $workOrderApplyMainStep
     */
    public static function updateWorkOrder($data, $params, $resCode, $resMsg, $step = WorkOrderFuyouInfoModel::DEFAULT_STEP_AUDIT, $status = WorkOrderFuyouLogModel::DEFAULT_FAIL_STATUS, $workOrderApplyMainStep = MissionEnum::STEP_7)
    {
        DB::beginTransaction();
        $info = WorkOrderFuyouInfoModel::getInfoByWorkOrderNo($data['workOrderNo']);
        if ($info) {
            WorkOrderFuyouInfoModel::setInfoById($info['id'], ['step' => $step]);//修改富友商户信息表-步骤
        }
        self::addLog($data['workOrderNo'], $params, $resCode, $resMsg, $status);
        //再修改工单状态
        WorkOrderApplyMainModel::saveStep($data['workOrderNo'], $workOrderApplyMainStep);
        if ($workOrderApplyMainStep == MissionEnum::STEP_8) {
            WorkOrderMissionModel::query()
                ->where('workOrderNo', $data['workOrderNo'])
                ->where('step', MissionEnum::STEP_7)
                ->update(['step' => $workOrderApplyMainStep]);
        }//同步任务流程记录
        DB::commit();
    }

    /**
     * 写入富友log
     * @param $workOrderNo
     * @param $params
     * @param $resCode
     * @param $resMsg
     * @param int $status
     * @param int $updatedByUid
     */
    public static function addLog($workOrderNo, $params, $resCode, $resMsg, $status = WorkOrderFuyouLogModel::DEFAULT_STATUS, $updatedByUid = 0)
    {
        $addData = [
            'workOrderNo'  => $workOrderNo,
            'content'      => json_encode($params),                                          //提交信息,json
            'res'          => json_encode(['code' => $resCode, 'msg' => $resMsg]),           //富友返回,json
            'status'       => $status,
            'updatedByUid' => $updatedByUid,
            'managerRes'   => $status == WorkOrderFuyouLogModel::DEFAULT_ADMIN_REJECT_STATUS ? $resMsg : "",
        ];
        WorkOrderFuyouLogModel::addLog($addData);//增加-富友自动进件日志记录表
    }

    /**
     * 通过店铺id查询对应店铺类型的配图
     * @param $shopId
     * @return mixed
     */
    public function getShopImg($shopId): array
    {
        $shopModelType = SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET;// 街边店
        $shopTypeInfo  = OpenShopMainProcessModel::getShopModelType($shopId);
        if ($shopTypeInfo && $shopTypeInfo->openShopSiteLocationRel) {
            if (optional($shopTypeInfo->openShopSiteLocationRel)['shopModelType'] == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
                $shopModelType = SiteLocationEnum::SHOP_MODEL_TYPE_MALL;//商场店
            }
        }
        $data = [];
        $list = json_decode(
            ConfigModel::query()
                ->where('module', 'fuyou')
                ->where('name', ConfigModel::FUYOU_SHOP_IMG)
                ->value('value') ?? '', true
        );
        if ($list) {
            foreach ($list as $v) {
                if ($v['type'] == $shopModelType) {
                    $data[] = $v;
                }
            }
        }
        return $data;
    }

    /**
     * 表单数据转化
     * @param $contentArray
     * @param $flagRepeatName
     * @return array
     */
    public function getFromData($contentArray, $flagRepeatName): array
    {
        $data['licenseType'] = '0';  //企业商户
        $data['business']    = '545';//经营范围代码（新开户则必填）
        $data['acntNm'] = $contentArray['legalPersonUsername'] ?? '';//入账卡户名
        $data['artifNm'] = $contentArray['legalPersonUsername'] ?? '';//法人姓名
        $data['realName'] = $data['mchntName'] = $contentArray['enterpriseName'];                                                            //商户名-商户真实名称(与营业执照上相同)
        $data['bankCode'] = $contentArray['companyBankCardBank'] ?? '';
        $data['interBankNo'] = $contentArray['companyBankCardBranchBank'] ?? '';
        if (isset($contentArray['businessType'])) {
            if ($contentArray['businessType'] == KfCashRegisterV2FormAttribute::BUSINESS_TYPE_SINGLE) {
                $data['licenseType'] = 'B';//个体工商户
                $data['business']    = '557';
            } else {//0 企业商户：营业执照（license_no填15位长的营业执照编号） 1 企业商户：三证合一（license_no填18位长的三证合一营业执照编号）
                if (strlen($contentArray['businessLicenseNumber']) > 15) {
                    $data['licenseType'] = '1';  //企业商户
                }
            }
        }
        $data['acntType'] = 1;// 入账卡类型：1：对公；2：对私
        if (isset($contentArray['settlementType'])) {
            $data['acntType'] = $contentArray['settlementType'];
        }
        if ($data['acntType'] == KfCashRegisterV2FormAttribute::SETTLEMENT_TYPE_PUBLIC) { //入账卡类型：1：对公
            $data['acntNm'] = $data['mchntName'];//入账卡户名-对公且法人入账，则入账卡户名和营业执照上商户名一致
        }
        $data['acntNo'] = $contentArray['companyBankCardNumber'] ?? ''; //入账卡号（不带长度位）
        $data['hasReserveAcnt'] = 0;//是否有备用对公银行账号(1：有，0：没有)
        if ($data['acntType'] == KfCashRegisterV2FormAttribute::SETTLEMENT_TYPE_PRIVATE) {//2：对私
            $data['acntNo']   = $contentArray['legalPersonBankCardNumber'] ?? '';
            $data['realName'] = $contentArray['legalPersonUsername'] ?? '';
            $data['bankCode'] = $contentArray['legalPersonBankCardBank'] ?? '';
            $data['interBankNo'] = $contentArray['legalPersonBankCardBranchBank'] ?? '';
            if ($data['licenseType'] != 'B') {//企业商户 对私传双账户信息 进件若为双账户时，此处必填 2 ，即对私结算
                $data['hasReserveAcnt']     = 1;  //是否有备用对公银行账号(1：有，0：没有) reserve_acnt 相关字段用于传双账户对公卡信息 注：双账户（指企业户对私结算）此处必须填上企业对公户
                $data['reserveAcntNo']      = $contentArray['companyBankCardNumber'] ?? '';//双账户对公卡卡号
                $data['reserveAcntNm']      = $contentArray['enterpriseName'] ?? '';//双账户对公卡户名
                $data['reserveInterBankNo'] = $contentArray['companyBankCardBranchBank'] ?? '';//双账户对公卡联行号
                $data['reserveIssBankNm']   = (new FuYouService)->getBankNameByCode($data['reserveInterBankNo']); //双账户对公卡开户行名称
                $data['reserveBankType']    = $contentArray['companyBankCardBank'] ?? '';//双账户对公卡行别
            }
        }
        $data['certifIdExpireDt'] = $data['cardStartDt'] = $data['licenseExpireDt'] = $data['licenseStartDt'] = '';
        if (isset($contentArray['legalPersonIdentityCardValidityPeriod'])) {//身份证开始-结束时间
            $certifIdExpireDtArr     = explode("-", $contentArray['legalPersonIdentityCardValidityPeriod']);
            $data['licenseStartDt']  = $certifIdExpireDtArr[0];
            $data['licenseExpireDt'] = $certifIdExpireDtArr[1] == '长期' ? '20991231' : $certifIdExpireDtArr[1];
        }

        if (isset($contentArray['businessLicenseRegistrationDate'])) {//营业执照-注册日期
            $data['cardStartDt'] = str_replace('-', '', $contentArray['businessLicenseRegistrationDate']);
        }
        if (isset($contentArray['businessLicenseValidityPeriodType']) && $contentArray['businessLicenseValidityPeriodType'] == KfCashRegisterV2FormAttribute::BUSINESS_LICENSE_TYPE_LONG) {//营业执照-证件期限
            $data['certifIdExpireDt'] = 20991231;//长期
        } elseif (isset($contentArray['businessLicenseEndDate'])) {//营业执照-结束时间
            $data['certifIdExpireDt'] = str_replace('-', '', $contentArray['businessLicenseEndDate']);
        }
        /*if (isset($contentArray['businessLicenseValidityPeriod'])) {//营业执照开始-结束时间
            $cardStartDtArr           = explode("-", $contentArray['businessLicenseValidityPeriod']['startTime']);
            $data['cardStartDt']      = $cardStartDtArr[0] . $cardStartDtArr[1] . $cardStartDtArr[2];
            $certifIdExpireDtArr      = explode("-", $contentArray['businessLicenseValidityPeriod']['endTime']);
            $data['certifIdExpireDt'] = $certifIdExpireDtArr[0] . $certifIdExpireDtArr[1] . $certifIdExpireDtArr[2];
        }*/
        $data['cityCd']         = $data['countyCd'] = $data['getCityName'] = '';
        $data['mchntShortname'] = ($contentArray['shopCode'] ?? '') . '夸父炸串店';
        if (isset($contentArray['businessCompanyArea'])) {//商户所在省市区
            $data['cityCd']         = $contentArray['businessCompanyArea']['cityCode'] ?? "";
            $data['countyCd']       = $contentArray['businessCompanyArea']['districtCode'] ? str_replace('#', '', $contentArray['businessCompanyArea']['districtCode']) : "";
            $getCityName            = (new FuYouService)->getCityNameByCode($data['cityCd']);
            $data['mchntShortname'] = $getCityName . $data['mchntShortname'];
        }
        $data['issBankNm'] = (new FuYouService)->getBankNameByCode($data['interBankNo']);

        $data['entryIDNumber'] = $contentArray['legalPersonIdentityCardNumber'] ?? '';               // 入账证件号 入账银行卡人的身份证号
        $data['acntArtifFlag'] = 1;                                                                  // 法人入账标识 0 :非法人入账，1：法人入账

        // 个体户非法人入账-其他人收款
        if (isset($contentArray['payeeType']) && $contentArray['payeeType'] == KfCashRegisterV2FormAttribute::PAYEE_TYPE_UN_CORPORATION) {
            $data['entryIDNumber'] = $contentArray['payeeIdentityCardNumber'] ?? '';      // 入账证件号 入账银行卡人的身份证号
            $data['acntNm']        = $contentArray['payeeUsername'] ?? '';                // 入账卡户名
            $data['acntArtifFlag'] = 0;                                                   // 法人入账标识 0 :非法人入账，1：法人入账
        }

        $data['mchntFullName'] = $data['mchntName'];// 商户全称，不能有特殊字符，仅可包含汉字、数字、字母
        if ($flagRepeatName) {// 重复时追加数字
            $data['flagRepeatName'] = $flagRepeatName + 1;
            $data['mchntFullName']  = $data['mchntName'] . '0' . $data['flagRepeatName']; // 商户全称，不能有特殊字符，仅可包含汉字、数字、字母
        }
        return $data;
    }

    /**
     * 获取城市名称
     * @param $code
     * @return mixed
     */
    public function getCityNameByCode($code)
    {
        return FyRegionModel::query()
            ->where('code', $code)
            ->where('level', 2)
            ->value('name');
    }

    /**
     * 获取支行名称
     * @param $code
     * @return mixed
     */
    public function getBankNameByCode($code)
    {
        return FyRegionBankModel::query()
            ->where('bankNo', $code)
            ->value('name');
    }


    /**
     * 商户终端信息采集报备接口
     * @param $data
     * @param $tmMode
     * @return mixed
     * @throws GuzzleException
     */
    public static function termCollect($data, $tmMode = FuYouRemote::TM_MODE_SYJ): int
    {
        $tmSerialNo = $data['mchnt_cd'] . '0000000001';
        if ($tmMode == FuYouRemote::TM_MODE_XCH) {
            $tmSerialNo = $data['mchnt_cd'] . '0000000002';
        }
        $params = [
            'mchnt_cd'        => $data['mchnt_cd'],                                                                                                     //商户号
            "handle_type"     => '00',                                                                                                                  //操作标识，取值范围：00：新增；01：修改；02：注销；
            'tm_mode'         => $tmMode,                                                                                                               //富友终端型号 JH-XCX=JH-小程序,JH-SYJ=JH-收银机
            'tm_device_state' => '00',                                                                                                                  //终端设备状态(启用、注销)00：启用；01：注销；
            'tm_serial_no'    => $tmSerialNo,                                                                                                           //如果厂家没有TUSN或者没有实体终端，本字段则填写：[mchnt_cd + SN号]或者[mchnt_cd + 合作方的虚拟终端号] eg:0002900F04686310000000001 此字段后续填入交易的reserved_terminal_info.serial_num字段中。
            'tm_contact_addr' => $data['contactAddr'],                                                                                                  //终端布放地(省-市-区-详细地址)
        ];
        (new FuYouRemote())->termCollect($params);//商户终端信息采集报备接口
        return 1;
    }

    /**
     * 5.3 发送一二级绑定
     * 富友收件邮箱：fuiou_sh@fuioupay.co
     * 富友返还告知已完成 邮件来源邮箱：fuiou_sh@fuioupay.com
     * @param string $workOrderNo
     * @param string $mchntName
     * @param string $fyMchntCd
     * @return array
     */
    public function secondaryBindingSendEmail(string $workOrderNo, string $mchntName, string $fyMchntCd): array
    {
        $title               = '一二级绑定';
        $appId               = config('fuyou.companyInfo.wechatAppid');                      //APPID
        $wechatPublicCompany = config('fuyou.companyInfo.wechatPublicCompany');              //公众号主体公司
        $mchNum              = config('fuyou.companyInfo.mchNum');                           //商户号
        $body = <<<STR
<html>
<body>

<p>辛苦参照正文内容 进行一二级绑定。</p>
<p>APPID：$appId</p>
<p>公众号主体公司：$wechatPublicCompany</p>
<p>商户号：$mchNum</p>

<table border="1" cellspacing="0">
<tr>
<td>商户名称</td>
<td>商户号</td>
<td>一二级关系</td>
</tr>
<tr>
<td>$wechatPublicCompany</td>
<td>$mchNum</td>
<td>一级</td>
</tr>
<tr>
<td>$mchntName</td>
<td>$fyMchntCd</td>
<td>二级</td>
</tr>
</table>

</body>
</html>
STR;
        $receiveEmail = config('fuyou.email.secondaryBindingAddress');//富友收件邮箱
        $receiveName  = config('fuyou.email.secondaryBindingName');//富友收件人
//        $receiveCCEmail = config('fuyou.email.secondaryCCBindingAddress');//抄送邮箱
        $receiveCCEmail = json_decode(
            ConfigModel::query()
                ->where('module', 'fuyou')
                ->where('name', 'secondaryCCBindingAddress')
                ->value('value') ?? '', true
        );//读config

        $res = (new EmailService)->sendEmail($receiveEmail, $receiveName, $title, $body, $receiveCCEmail);

        self::addLog(
            $workOrderNo, ['workOrderNo' => $workOrderNo, 'mchntName' => $mchntName, 'fyMchntCd' => $fyMchntCd],
            $res['code'], $res['msg'], WorkOrderFuyouLogModel::DEFAULT_STEP_SEND_SECOND_BINDING_EMAIL
        );//记录发送邮件log
        Log::info("富友进件2.0-发送一二级绑定邮件请求返回：", ['workOrderNo' => $workOrderNo, 'mchntName' => $mchntName, 'fyMchntCd' => $fyMchntCd, 'res' => $res]);
        return $res;
    }


    /**
     * 5.2 发送前置密钥申请
     * 富友收件邮箱：techsupport@fuioupay.com
     * 富友返还密钥、前缀 邮件来源邮箱：fuiou_wl@fuioupay.com
     * @param string $workOrderNo
     * @param string $mchntName
     * @param string $fyMchntCd
     * @return array
     */
    public function preSecretApplySendEmail(string $workOrderNo, string $mchntName, string $fyMchntCd): array
     {
        $title               = '前置系统对接上线申请';
        $body = <<<STR
<html>
<body>


<p>辛苦审核，盖章后补</p>

<table border="1" cellspacing="0">
<tr>
<td>商户名称</td>
<td>商户号</td>
</tr>
<tr>
<td>$mchntName</td>
<td>$fyMchntCd</td>
</tr>
</table>

</body>
</html>
STR;
        $receiveEmail = config('fuyou.email.preSecretApplyAddress');//富友收件邮箱
        $receiveName  = config('fuyou.email.preSecretApplyName');//富友收件人
        $res          = (new EmailService)->sendEmail($receiveEmail, $receiveName, $title, $body);

         self::addLog(
             $workOrderNo, ['workOrderNo' => $workOrderNo, 'mchntName' => $mchntName, 'fyMchntCd' => $fyMchntCd],
             $res['code'], $res['msg'], WorkOrderFuyouLogModel::DEFAULT_STEP_SEND_SECOND_BINDING_EMAIL
         );//记录发送邮件log
         Log::info("富友进件2.0-前置系统对接上线申请：", ['workOrderNo' => $workOrderNo, 'mchntName' => $mchntName, 'fyMchntCd' => $fyMchntCd, 'res' => $res]);
        return $res;
    }

    /**
     * 接收邮件处理
     * @param $emailData
     * @return bool
     */
    public function receiveEmail($emailData): bool
    {
        if (!$emailData) {
            return false;
        }
        if ($emailData['body'] && $emailData['subject']) {
            $type = mb_strstr($emailData['subject'], '商户账号通知');                     //匹配商户账号通知
            $typeSecondaryBinding = mb_strstr($emailData['subject'], 'Re: 一二级绑定');   //匹配一二级绑定
            $typeSecretApply = mb_strstr($emailData['subject'], '业管平台移动前置系统秘钥');//匹配业管平台移动前置系统秘钥
            if ($type) {//接收账号、密码
                /*if ($emailData['fromEmail'] == config('fuyou.email.receivePreSecretApplyAddress')) {//匹配发件人邮箱

                }*/
                $searchTxt   = mb_strstr($emailData['body'], "商户[");//找到对应商户名位置
//                var_dump($searchTxt);//"商户[上海市闵行区白娇小吃店]已开通，凭用户名[MX5499096]，密码[088096],下载[富掌柜商户版]APP交易随时推，wmp.fuioupay.com可随时查
                if($searchTxt){
                    $start       = mb_strpos($searchTxt, "商户[");
                    $end         = mb_strpos($searchTxt, "]");
                    $companyName = mb_substr($searchTxt, $start + 3, $end - $start - 3);//商户名
                }
                $searchTxt = mb_strstr($emailData['body'], "用户名[");//找到对应用户名位置
                if($searchTxt){
                    $start     = mb_strpos($searchTxt, "用户名[");
                    $end       = mb_strpos($searchTxt, "]");
                    $mchName   = mb_substr($searchTxt, $start + 4, $end - $start - 4);//用户名
                }
                $searchTxt   = mb_strstr($emailData['body'], "密码[");//找到对应密码位置
                if($searchTxt){
                    $start       = mb_strpos($searchTxt, "密码[");
                    $end         = mb_strpos($searchTxt, "]");
                    $mchPassword = mb_substr($searchTxt, $start + 3, $end - $start - 3);//密码
                }
                if (isset($companyName) && $companyName && isset($mchName) && $mchName && isset($mchPassword) && $mchPassword) {
                    $info = WorkOrderFuyouInfoModel::getInfoByCompanyName($companyName);
                    if (!$info) {
                        $info = WorkOrderFuyouInfoModel::getInfoByCompanyName(self::trimCompanyNameNumber($companyName));
                        if (!$info){
                            return false;
                        }
                    }
                    $step = WorkOrderFuyouInfoModel::DEFAULT_STEP_EMAIL_MCH_NAME_PASSWORD;
                    //修复数据时状态已完成不进行步骤变更
                    if ($info['step'] == WorkOrderFuyouInfoModel::DEFAULT_STEP_SUC){
                        $step = WorkOrderFuyouInfoModel::DEFAULT_STEP_SUC;
                    }
                    WorkOrderFuyouInfoModel::setInfoById(
                        $info['id'],
                        [
                            'mchName'     => $mchName,
                            'mchPassword' => $mchPassword,
                            'step'        => $step,
                        ]
                    );
                }
            }
            if ($typeSecondaryBinding) {                                //接收一二级绑定返回
                /*if ($emailData['fromEmail'] == config('fuyou.email.secondaryBindingAddress')) {//匹配发件人邮箱

                }*/
                $searchTxt = mb_strstr($emailData['body'], "你好，已处理");//找到对应你好，已处理位置
                if ($searchTxt) {
                    preg_match_all('/<td(.*?)>(.*?)<\/td>/s', $emailData['body'], $matches);
                    $data      = $matches[2];
                    $fyMchntCd = '';
                    for ($i = 0, $len = count($data); $i < $len; $i = $i + 4) {
                        if ($i == 4) {
//                            var_dump($data[$i + 3]);//<span>0002900F5499096</span>
                            $fyMchntCd = str_replace('<span>', '', $data[$i + 3]);//商户号
                            $fyMchntCd = str_replace('</span>', '', $fyMchntCd);//商户号
                        }
                    }
                    if ($fyMchntCd) {
                        $info = WorkOrderFuyouInfoModel::getInfoByFyMchntCd($fyMchntCd);
                        if (!$info) {
                            return false;
                        }
                        WorkOrderFuyouInfoModel::setInfoById(
                            $info['id'], [
                                'secondaryBindingStatus' => WorkOrderFuyouInfoModel::DEFAULT_SYSTEM_APPLY_STATUS_SUC,
                                'step'                   => WorkOrderFuyouInfoModel::DEFAULT_STEP_EMAIL_MCH_NAME_PASSWORD,
                            ]
                        );
                    }
                }
            }
            if ($typeSecretApply) {
                /*if ($emailData['fromEmail'] == config('fuyou.email.receivePreSecretApplyAddress')) {//匹配发件人邮箱

                }*/
                preg_match_all('/<td(.*?)>(.*?)<\/td>/s', $emailData['body'], $matches);
                $data = $matches[2];
                $fyMchntCd = $mchKey = $orderPrefix = '';
                if ($data) {
                    $fyMchntCd = $data[1] ?? "";
                    $mchKey = $data[5] ?? "";
                    $orderPrefix = $data[7] ?? "";
                    $orderPrefix = substr($orderPrefix, 0, mb_strpos($orderPrefix, "（生产订单号"));
                }
//                [
//                    0 => "商户号:"
//  1 => "0002900F5499096"
//  2 => "商户名:"
//  3 => "上海市闵行区白娇小吃店\t"
//  4 => "商户前置系统生产交易秘钥:"
//  5 => "342c0ef06efc11edbbdc8ad34d134adf"
//  6 => "订单前缀:"
//  7 => "10841（生产订单号mchnt_order_no字段前面需加上富友分配的5位订单前缀）"
//]
                if ($fyMchntCd) {
                    $info = WorkOrderFuyouInfoModel::getInfoByFyMchntCd($fyMchntCd);
                    if (!$info) {
                        return false;
                    }
                    WorkOrderFuyouInfoModel::setInfoById(
                        $info['id'], [
                            'mchKey'               => $mchKey,
                            'orderPrefix'          => $orderPrefix,
                            'preSystemApplyStatus' => WorkOrderFuyouInfoModel::DEFAULT_SYSTEM_APPLY_STATUS_SUC,
                            'step'                 => WorkOrderFuyouInfoModel::DEFAULT_STEP_EMAIL_MCH_NAME_PASSWORD,
                        ]
                    );
                }
            }
        }
        return true;
    }

    /**
     * 兼容多一个营业执照搞多个店，富有返回名称带序号
     * @param string $companyName
     * @return string
     */
    public static function trimCompanyNameNumber(string $companyName): string
    {
        //北京悦鲜餐饮有限公司02
        $len       = mb_strlen($companyName);
        $last2Char = mb_substr($companyName, $len - 2, $len);
        if (is_numeric($last2Char)) {
            return mb_substr($companyName, 0, $len - 2);
        }
        return $companyName;
    }

}
